package main

import (
	"fmt"
	mqtt "github.com/eclipse/paho.mqtt.golang"
	"time"
)

func main() {
	opts := mqtt.NewClientOptions().AddBroker("tcp://127.0.0.1:1883")
	opts.SetClientID("stand")
	opts.SetCleanSession(true)
	opts.SetAutoReconnect(true)

	opts.SetOnConnectHandler(func(client mqtt.Client) {
		fmt.Println(time.Now().String(), "连接上了")
		client.Subscribe("/dev/1/2/3", 0, func(client mqtt.Client, message mqtt.Message) {
			fmt.Println(message.Topic(), string(message.Payload()))
		})
	})

	opts.SetConnectionLostHandler(func(client mqtt.Client, err error) {
		fmt.Println(time.Now().String(), "断开连接")
	})


	c := mqtt.NewClient(opts)
	token := c.Connect()
	if token.Wait() && token.Error() != nil {
		panic(token.Error())
	}


	for {
		time.Sleep(time.Second)
		c.Publish("/dev/1/2/3", 0, false, []byte("hello"))
	}
}
